package top.fwpsl.netty.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.lang.reflect.Proxy;

/**
 * @auther: 风戏fw
 * @date: 2021/2/5
 * @description: 用Netty实现客户端的代理类，采用Netty自带的ObjectEncode和ObjecDecode作为编码解码（为降低复杂度，
 * * 这里并没有使用第三方的编码解码器），当然实际开发中也可以采用JSON或XML
 */
public class NettyRpcProxy {

    //根据结构创建代理对象
    public static Object create(Class target) {
        return Proxy.newProxyInstance(target.getClassLoader(), new Class[]{target}, (proxy, method, args) -> {
            //封装ClassInfo
            ClassInfo classInfo = new ClassInfo();
            classInfo.setClassName(target.getName());
            classInfo.setMethodName(method.getName());
            classInfo.setObjects(args);
            classInfo.setTypes(method.getParameterTypes());
            //开始用Netty发送数据
            EventLoopGroup group = new NioEventLoopGroup();
            ResultHandler resultHandler = new ResultHandler();
            try {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {

                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                //编码器
                                pipeline.addLast("encoder", new ObjectEncoder())
                                        //解码器,构造方法第一个参数设置二进制的最大字节数,第二个参数设置具体使用哪个类解析器
                                        .addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)))
                                        //客户端业务处理类
                                        .addLast("handler", resultHandler);
                            }
                        });
                ChannelFuture future = bootstrap.connect("127.0.0.1", 9990).sync();
                future.channel().writeAndFlush(classInfo).sync();
                future.channel().closeFuture().sync();
            } finally {
                group.shutdownGracefully();
            }
            return resultHandler.getResponse();
        });
    }
}
